const buf = Buffer.from("Hi");
console.log(buf); //<Buffer 48 69>
console.log((0x48).toString(2), (0x69).toString(2)); //01001000 01101001
// 010010 000110 100100
let rawBase64 =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
console.log(buf.toString("base64")); // SGk=,Base64编码要求把3个8位字节（3*8=24）转化为4个6位的字节（4*6=24），之后在6位的前面补两个0，形成8位一个字节的形式。 如果剩下的字符不足3个字节，则用0填充，输出字符使用'='，因此编码后输出的文本末尾可能会出现1或2个'='
let newBuf = rawBase64[0b010010] + rawBase64[0b000110] + rawBase64[0b100100];
console.log(newBuf); //SGk
console.log(buf.length); //2

// buffer声明方法alloc或者allocUnsafe
let copyBuf = Buffer.alloc(2);
buf.copy(copyBuf, 0, 0, 2);
console.log(copyBuf, copyBuf.toString()); //<Buffer 48 69> Hi

// buffer的slice方法
const sliceBuf = buf.slice(0, 1);
console.log(sliceBuf, sliceBuf.toString()); //<Buffer 48> H
sliceBuf[0] = 121; //buffer存放的内存地址，改变截取值的时候，会把原来的值改掉
console.log(buf, buf.toString()); //<Buffer 79 69> yi

// Uint16Array
const unit16 = new Uint16Array(2);
unit16[0] = 2322;
unit16[1] = 5000;
const unit16Buf = Buffer.from(unit16.buffer);
console.log(unit16Buf.toString());

// concat
const buf1 = Buffer.from("buffer");
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1, buf2);
const concatBuf = Buffer.concat([buf1, buf2]);
console.log(concatBuf.toString());

// ifBuffer是不是buffer
console.log(Buffer.isBuffer(buf1));
console.log(Buffer.isBuffer(true));

// 扩展buffer方法
Buffer.prototype.copyBuf = function (
  target,
  targetStart,
  sourceStart,
  sourceEnd
) {
  for (let i = 0; i < sourceEnd - sourceStart; i++) {
    target[targetStart + i] = this[sourceStart + i];
  }
};
const helloBuf = Buffer.from("helloBuf好");
let newCopyBuf = Buffer.alloc(10);
helloBuf.copyBuf(newCopyBuf, 0, 0, 5);
console.log(helloBuf, newCopyBuf);
console.log(newCopyBuf.toString());

// 模拟Buffer.concat方法
Buffer.concatBuf = function (
  list,
  length = list.reduce((a, b) => a + b.length, 0)
) {
  let buff = Buffer.alloc(length);
  let offset = 0;
  list.forEach((b) => {
    b.copy(buff, offset);
    offset += b.length;
  });
  return buff;
};
let b1 = Buffer.from('好');
let b2 = Buffer.from('天');
let b3 = Buffer.from('气');
let newConcatBuf = Buffer.concatBuf([b1, b2, b3]);
console.log(newConcatBuf.toString());

// 自定义Buffer原型上的spilt方法，可以按照某字符分割buffer数据
let buffer = Buffer.from(`好天气
好天气
好天气`);
Buffer.prototype.split = function(dep){
    let len = Buffer.from(dep).length;
    let offset = 0;
    let result = [];
    let current;
    // 把找到的位置索引赋值给current
    while((current = this.indexOf(dep, offset)) !== -1){
        result.push(this.slice(offset, current)); //每次截取的数据添加到数组
        offset = current + len; // 增加查找偏移量
    }
    result.push(this.slice(offset));
    return result;
}
console.log(buffer.split('\n'));

